$(document).ready(function () {
  $('form').submit(function() {
    if ($('#locked').val() === '1') {
      return false;
    }
  });

  $('a').each(function(){
    //$(this).attr('title', $(this).html());
    });

  $('.show_receipt').click(function () {
    var id = $(this).attr('name');
    $.ajax({
      url: $('#frontcontroller').val() + '/receipt/print/'+id,
      success: function (data) {
        $('#content_id').html(data);
        //$('#popup').css('display', 'block');
        printReceipt();
      }
    });
  });

  $('#close_popup').click(function () {
    $('#popup').css('display', 'none');
  });

  $('#frm_date_of_birth_year').addClass('txtfeid_02_2').removeClass('txtfeid_02');
  $('#frm_card_date_year').addClass('txtfeid_02_2').removeClass('txtfeid_02');

  if ($('#accordion').attr('id')) {
    $('.acc_body').hide();
    $('.acc_body:first').show();

    $('.acc_head,.posterdetail').css('cursor', 'pointer');
    
    $('.buynow').click(function(e) {
      $('#offer_' + $(this).attr('rel')).submit();
      e.stopPropagation();
    });

    $('.acc_head').click(function() {
      $('.acc_body').slideUp('fast');
      if ($(this).next('.acc_body').is(':visible') === false) {
        $(this).next('.acc_body').slideDown('fast');
      }
    });
    
    $('.quantity_box').click(function(e) {
      e.stopPropagation();
    });
  }
  
  $('#frm_date').DatePicker({
    date: $('#frm_date').val(),
    current: $('#frm_date').val(),
    format:'d/m/Y',
    starts: 1,
    onBeforeShow: function(){
      var default_date = $('#frm_date').val() ? $('#frm_date').val() : $('#current_date').val();
      $('#frm_date').DatePickerSetDate(default_date, true);
    },
    onChange: function(formated, dates){
      $('#frm_date').val(formated);
      $('#frm_date').DatePickerHide();
    }
  });

  if ($('#frm_number_of_tickets').val()) {
    calculateTotalPrice();
  }

  $('#frm_location').autocomplete($('#frontcontroller').val() + '/ajax-location-search', {
    width: function () {
      return $('#frm_location').width();
    } ,
    selectFirst: false
  }).result(function(event, data, formatted) {
    var key = data.toString().split('key:');
    var prod_id = key[1];
  });

  $('#frm_movie_title').autocomplete($('#frontcontroller').val() + '/ajax-movie-search', {
    width: function () {
      return $('#frm_movie_title').width();
    } ,
    selectFirst: false
  }).result(function(event, data, formatted) {
    var key = data.toString().split('key:');
    var prod_id = key[1];
  });
});

function printReceipt() {
  $('#print_receipt').click(function () {
    $('#receipt_content').printElement();
  });
}

function calculateTotalPrice() {
  $('#price label').html('$' + formatCurrency($('#frm_number_of_tickets').val() * $('#unit_price').val()));
}

function formatCurrency(num) {
  num = isNaN(num) || num === '' || num === null ? 0.00 : num;
  return parseFloat(num).toFixed(2);
}